package com.sisyphus.spinach.helper;

import android.os.Handler;
import android.os.Looper;

import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleEventObserver;
import androidx.lifecycle.LifecycleOwner;

/**
 * 自动绑定页面生命周期，当destroy时会自动移除消息
 */
public class LifecycleHandler implements LifecycleEventObserver {

    private Runnable r;
    private final Handler mHandler;

    public LifecycleHandler(LifecycleOwner lifecycleOwner, Looper looper) {
        lifecycleOwner.getLifecycle().addObserver(this);
        this.mHandler = new Handler(looper);
    }

    /**
     * 发送延时消息
     */
    public final boolean postDelayed(@NonNull Runnable r, long delayMillis) {
        this.r = r;
        return mHandler.postDelayed(r, delayMillis);
    }


    @Override
    public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
        if (event == Lifecycle.Event.ON_DESTROY) {
            mHandler.removeCallbacks(this.r);
        }
    }

}
